package com.code.family.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.code.family.entity.pojo.*;
import com.code.family.service.AccountsService;
import com.code.family.service.TransactionsService;
import com.code.family.utils.ResultVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 记账
 */
@RestController
@RequestMapping("/api/transaction")
@Slf4j
@RequiredArgsConstructor
public class TransactionsController {

    private final TransactionsService transactionsService;
    private final AccountsService accountsService;

    /**
     * 新增收支记录
     */
    @PostMapping
    public ResultVo add(@RequestBody Transactions transaction) {
        // 判断账户余额是否足够和账户是否正确
        int accountId = transaction.getAccountId();
        Accounts accounts = new Accounts();
        accounts.setId(accountId);
        // 查询账户余额
        // 创建LambdaQueryWrapper
        LambdaQueryWrapper<Accounts> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Accounts::getId, accountId);
        Accounts accounts1 = accountsService.getOne(queryWrapper);
        float balance = accounts1.getBalance();
        // 0：收入/1：支出
        int type = transaction.getType();
        if (type == 0) {
            // 收入
            // 计算新的账户余额
            float newBalance = balance + transaction.getAmount();
            accounts.setBalance(newBalance);
        } else if (type == 1) {
            // 支出
            if (balance - transaction.getAmount() < 0) {
                return ResultVo.error("账户余额不足,请检查余额");
            }
            // 计算新的账户余额
            float newBalance = balance - transaction.getAmount();
            accounts.setBalance(newBalance);
        }
        // 更新账户余额
        accountsService.updateById(accounts);
        // 添加时间
        transaction.setCreatedAt(new Date());
        transaction.setUpdatedAt(new Date());
        boolean result = transactionsService.add(transaction);
        return ResultVo.success(result);
    }

    /**
     * 删除收支记录
     */
    @DeleteMapping("/{id}")
    public ResultVo delete(@PathVariable Integer id) {
        // 根据id删除
        boolean result = transactionsService.delete(id);
        return ResultVo.success(result);
    }

    /**
     * 根据ID查找账单
     */
    @GetMapping("/{id}")
    public ResultVo selectById(@PathVariable Integer id) {
        List<Transactions> result = transactionsService.selectById(id);
        return ResultVo.success(result);
    }


    /**
     * 修改收支记录
     */
    @PutMapping
    public ResultVo update(@RequestBody Transactions transaction) {
        // 添加时间
        transaction.setUpdatedAt(new Date());
        log.info("update transaction: {}", transaction);
        boolean result = transactionsService.update(transaction);
        return ResultVo.success(result);
    }

    /**
     * 多表联查,分页获取记账列表
     */
    @GetMapping
    public ResultVo getList(PageParamType param) {
        // 条件查询
        LambdaQueryWrapper<Transactions> queryWrapper = new LambdaQueryWrapper<>();
        // 获取总记录数
        int total = (int) transactionsService.count(queryWrapper);
        // 条件查询
        List<Transactions> pageList = transactionsService.find(param);
        // 封装分页数据
        PageData pageData = new PageData();
        pageData.setRecords(pageList);
        pageData.setTotal(total);
        pageData.setCurrent(param.getCurrentPage());
        pageData.setSize(param.getPageSize());
        pageData.setPages(pageList.size() / param.getPageSize() + 1);
        // 返回结果
        return ResultVo.success(pageData);
    }

}
